<?php

namespace generate\traits;

trait Tools
{
    public function getMiddleStr($str, $leftStr, $rightStr)
    {
        $left  = strpos($str, $leftStr);
        $right = strpos($str, $rightStr, $left);
        if ($left < 0 or $right < $left) return '';
        return substr($str, $left + strlen($leftStr), $right - $left - strlen($leftStr));
    }


    /**
     * @param $field_name
     * @param $field_type
     * @return mixed
     * 常用类型
     * tinyint,smallint,mediumint,int,bigint,float,double,decimal
     * char,varchar,tinytext/tinyblob,text/blob,longtext/longblob
     * date,datetime,timestamp,time,year
     */
    public function getFieldInfo($field_name, $field_type)
    {
        //默认类型
        $type = 'tinyint';
        //默认长度
        $length = 10;
        //默认小数点后位数
        $digit = 0;
        $fieldArr = [
            'tinyint',
            'smallint',
            'mediumint',
            'int',
            'bigint',
            'float',
            'double',
            'decimal',
            'char',
            'varchar',
            'tinytext',
            'tinyblob',
            'text',
            'blob',
            'longtext',
            'longblob',
            'date',
            'datetime',
            'timestamp',
            'time',
            'year',
            'json'
        ];
        if (in_array($field_type, $fieldArr)) {
            $type = $field_type;
            $length = $this->getMiddleStr($field_type, $field_type . '(', ')');
        }

        return [
            'name'   => $field_name,
            'type'   => $type,
            'length' => $length,
            'digit'  => $digit,
        ];
    }
}
